

var gallerij = {};

gallerij.build = function() {
	
	Ti.include('picture_info.js');
	    
	win = Ti.UI.createWindow ({
	    backgroundColor: '#fff',
	    layout: 'vertical',
	    navBarHidden:true,
	});                  
	    
	var galleryView = Ti.UI.createView({
	   //layout: 'horizontal',
       width: Ti.UI.FILL,
       
       height: Ti.UI.FILL 
	    
	});
	
	var header = Ti.UI.createView({
	   width: Ti.UI.FILL,
	   height: '85dip',
	   backgroundImage: '/images/header.png',
	   top: 0
	});
	var title = Ti.UI.createLabel({
	    color: '#fff',
	    font: {fontSize:'20dip' },
	    top: '18dip',
	})
    title.text = 'Gallerij';
    
	header.add(title);
	
	if(Ti.Platform.name != 'android')
    {
        var backButton = Ti.UI.createButton({
            title: 'Terug', 
            left: '10dip',
            top: '10dip',
            width: Ti.UI.SIZE,
            height: Ti.UI.SIZE,
            color: '#090C16',    
            visible: true
        });
        
        backButton.addEventListener('click', function() {
            win.close;
        });
        
        header.add(backButton);
  	}
	
	galleryView.add(header);
	
	var galleryScrollView = Ti.UI.createScrollView({
       //layout: 'horizontal',
        width: Ti.UI.FILL,
        top: 85,
        bottom: 0
    });
    
    galleryScrollView.addEventListener('reloadGallery', function(e){
        
        alert('fired');
        
        galleryScrollView = Ti.UI.createScrollView({
           //layout: 'horizontal',
            width: Ti.UI.FILL,
            top: 85,
            bottom: 0
        });
        
        loadGallery();
        
    });
	
	loadGallery();
	
	galleryView.add(galleryScrollView);
	
	win.add(galleryView);
	
	win.open();
	
	function loadGallery(){
	    
	    //progressbar: only appears if fotoArray contains at least 10 pics
    var fotoArray = loadSavedImages();
    
    var pb = gallerij.pb;
    
    var screenWidth = Ti.Platform.displayCaps.platformWidth;
    var screenHeight = Ti.Platform.displayCaps.platformHeight;
    
    if(screenHeight < screenWidth)
    {
        screenWidth = screenHeight;
    }
    
    var photoWidth = (screenWidth / 4) - 2;
    
    var posLeft = 1;
    var posTop = 0;
    var newRowCounter = 0;
    
    for(var i = 0; i < fotoArray.length; i++)
    {   
        
        var image = Globals.getFile(fotoArray[i].fotonaam);
        if(image != null)
        {
        
            if(Ti.Platform.name == 'android')
            {
                
            }
            else
            {
               image = image.read();
               image = image.imageAsThumbnail(photoWidth);   
            }
            
           
            
            var picture = Ti.UI.createImageView({
               width: photoWidth,
               height: photoWidth,
               image: image,
               top: posTop,
               left: posLeft,
               onderwerp: fotoArray[i].onderwerp,
               omschrijving: fotoArray[i].omschrijving,
               pictureId: fotoArray[i].fotoid,
               fotonaam: fotoArray[i].fotonaam
            });
            
            if(Ti.Platform.name == 'android')
            {
               picture.borderWidth = 1;
               picture.borderColor = '#fff';
            }
            
            picture.addEventListener('click', function(e){
                
               pictureInfo.build(e.source.image, e.source.onderwerp, e.source.omschrijving); 
                
            });
            
            
            if (Ti.Platform.osname == "android") {
                picture.addEventListener('longclick', function(e){
                    
                    removePicture(e);
                    
                });
            }
            else
            {
                picture.addEventListener('longpress', function(e){
                
                    removePicture(e);
                });
                
            }
            
            galleryScrollView.add(picture);
            
            if(newRowCounter == 3)
            {
                posTop += photoWidth + 2;
                posLeft = 1;
                
                newRowCounter = 0;
            }
            else
            {
                posLeft += photoWidth + 2;
                newRowCounter++;
            }
        }
        //progressbar progress
        if (i%8 == 7) {
            if(pb != null) {
                pb.setValue(pb.value+4);
            }
        }
    }
    
    
    if(pb != null) pb.hide();
	}
	
	function removePicture(e)
	{
	    var pictureId = e.source.pictureId;
	    
	    var alertMsg = Ti.UI.createAlertDialog({
                cancel: 1,
                buttonNames: ['OK', 'Annuleer'],
                message: 'Weet u zeker dat u deze afbeelding wilt verwijderen?',
                title: 'Verwijder'
        });
        
        alertMsg.addEventListener('click', function( evt ) {
                if( evt.index === 0 ) {
                    removePictureFromXml(pictureId);
                    
                    //alert(e.source.fotonaam);
                    
                    var imageFile = Globals.getFile(e.source.fotonaam);
//                     
                    if(imageFile.exists())
                    {
                        imageFile.deleteFile();
                        alert('Foto Verwijderd!');
                    }
                    
                    
                    e.source.image = '';
                    
                }
         });
         
         alertMsg.show();
	}
	
	function removePictureFromXml(pictureId)
	{
	    Ti.Media.vibrate([0, 35]);
	    
	    var deleted = false;
        
        var target = Globals.getSupportFile('fotos.xml');
        
        if(target.exists()) {
            var xmltext = target.read().text;
            var doc = Ti.XML.parseString(xmltext);
            var root = doc.getDocumentElement();
            
            var nodelist = doc.getElementsByTagName("foto");
            
            for(var i = 0; i<nodelist.length; i++ ) {
                if (nodelist.item(i).getAttribute("fotoid") == pictureId) {         
                    root.removeChild(nodelist.item(i));
                    deleted = true;
                    //galleryScrollView.fireEvent('reloadGallery');
                    
                }
            }
            target.write(Ti.XML.serializeToString(doc));
        }
        
        return deleted;
	}
	
	function loadSavedImages()
	{
	    var xmlFile = Globals.getSupportFile("fotos.xml");
        
        var fotoArray = [];
        
        if(xmlFile.exists()) {
            var xmltext = xmlFile.read().text;
            var doc = Ti.XML.parseString(xmltext);
            
            var fotoLijst = doc.documentElement.getElementsByTagName("foto");
            
            if(fotoLijst.length >= 10) {
            	createProgressBar(fotoLijst.length);
				var pb = gallerij.pb;
			}
            
            for(var i = 0; i< fotoLijst.length;i++) {
                
                var fotoid = fotoLijst.item(i).getAttribute("fotoid");
                var fotonaam = unescape(fotoLijst.item(i).getAttribute("name"));
                var leerlingid = unescape(fotoLijst.item(i).getAttribute("leerlingid"));
                var tag = unescape(fotoLijst.item(i).getAttribute("tag"));
                var onderwerp = unescape(fotoLijst.item(i).getAttribute("onderwerp"));
                var omschrijving = unescape(fotoLijst.item(i).getAttribute("omschrijving"));
                var datum = unescape(fotoLijst.item(i).getAttribute("datum"));
                
                
                
                var foto = new fotoObject(fotoid, fotonaam, leerlingid, tag, onderwerp, omschrijving, datum);
                
                fotoArray.push(foto);
                
                //progressbar progress
        		if (i%8 == 7) {
			    	if(pb != null) {
			    		pb.setValue(pb.value+4);
			    	}
    			}
                
            }
        }
        
        return fotoArray;
	    
	}
	
	function createProgressBar(maxSize) {
				gallerij.pb = Titanium.UI.createActivityIndicator({
			        bottom:10, 
			        height:50,
			        width:50,
					location:Titanium.UI.ActivityIndicator.DIALOG,
					type:Titanium.UI.ActivityIndicator.DETERMINANT,
					message:'Loading...',
					min:0,
					max: maxSize,
					value:0
				});
				
				if(Titanium.Platform.name != 'android') {
					win.add(gallerij.pb);
				}
				gallerij.pb.show();
	}
	
}